<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-row class="mb-4 text-right">
          <el-button type="primary" @click="handleCreate">&emsp;新增&emsp;</el-button>
        </el-row>
      </div>
      <div v-loading="listLoading" class="item">
        <el-table ref="dataList"
                  :data="menuList" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
                  border row-key="id" style="width:100%;margin-bottom: 20px;"
        >
          <el-table-column label="序号" prop="id" sortable></el-table-column>
          <el-table-column label="边框名称" prop="name"></el-table-column>
          <el-table-column label="边框类型" prop="type_text"></el-table-column>
          <el-table-column label="效果图" min-width="100px" prop="srcList">
            <template slot-scope="scope">
              <el-image 
                style="width: 100px; height: 100px"
                :src="scope.row.index_img"
                :preview-src-list="scope.row.srcList">
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
              <el-image 
                style="width: 100px; height: 100px"
                :src="scope.row.recommend_img"
                :preview-src-list="scope.row.srcList">
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
              <el-image 
                style="width: 100px; height: 100px"
                :src="scope.row.room_img"
                :preview-src-list="scope.row.srcList">
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="create_time"></el-table-column>
          <el-table-column label="操作" width="260px">
            <template slot-scope="scope">
              <el-button icon="el-icon-edit" plain size="mini"
                         type="success" @click="handleUpdateOrPresent(scope.row,'update')"
              >编辑
              </el-button>
              <el-button icon="el-icon-present" plain size="mini"
                         type="primary" @click="handleUpdateOrPresent(scope.row,'present')"
              >赠送
              </el-button>
              <el-button icon="el-icon-delete" plain
                         size="mini" type="danger" @click="handleDelete(scope.row)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <cus-pagination :limit.sync="listQuery.perPage" :page.sync="listQuery.page" :total="total"
                        @pagination="getList"
        />
      </div>
    </el-card>
    <!-- 删除弹框 -->
    <el-dialog :visible.sync="deleteDialogVisible" title="确定删除吗?" width="435px">
      <span><em style="font-style:normal;color:red">删除后不可恢复</em>，你还要继续吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmDelete">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 新增/编辑弹框 -->
    <el-dialog v-dialogDrag :title="titleMap[dialogStatus]"
               :visible.sync="dialogFormVisible"
               @close="handleCloseDialog('editRulesForm')"
    >
      <el-form
        ref="editRulesForm"
        :model="editRulesForm"
        :rules="editRulesFormRules"
        class="demo-ruleForm"
        label-width="120px"
      >
        <el-form-item label="边框名称" prop="name">
          <el-input
            v-model="editRulesForm.name"
            clearable
            maxlength="20"
            show-word-limit
            placeholder="请输入名称"
            :disabled="dialogStatus === 'present'"
          ></el-input>
        </el-form-item>
        <el-form-item label="边框类型" prop="type">
          <el-select
            v-model="editRulesForm.type"
            clearable
            placeholder="请选择类型"
            :disabled="dialogStatus === 'present'"
          >
            <el-option
              v-for="item in adType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="editRulesForm.type === 1 || editRulesForm.type === 2" label="首页效果图" prop="index_img">
          
          <el-upload
            :http-request="customizeUpload"
            :on-success="handleSuccess"
            :show-file-list="false"
            action=""
            class="avatar-uploader"
            :disabled="dialogStatus === 'present'"
          >
            <img v-if="editRulesForm.index_img"
                 :src="editRulesForm.index_img"
                 class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item v-if="editRulesForm.type === 1" label="推荐效果图" prop="recommend_img">
          <el-upload
            :disabled="dialogStatus === 'present'"
            :http-request="customizeUpload"
            :on-success="handleSuccess1"
            :show-file-list="false"
            action=""
            class="avatar-uploader"
          >
            <img v-if="editRulesForm.recommend_img" :src="editRulesForm.recommend_img" class="avatar"/>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item v-if="editRulesForm.type === 1" label="房间效果图" prop="room_img">
          <el-upload
            :http-request="customizeUpload"
            :on-success="handleSuccess2"
            :show-file-list="false"
            action=""
            class="avatar-uploader"
            :disabled="dialogStatus === 'present'"
          >
            <img v-if="editRulesForm.room_img" :src="editRulesForm.room_img" class="avatar"/>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="房间ID" prop="room_id" v-if="dialogStatus === 'present' && editRulesForm.type===1">
          <el-input
            v-model="editRulesForm.room_id"
            clearable
            placeholder="请输入房间ID（多个请用英文逗号隔开）"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户ID" prop="user_id" v-if="dialogStatus === 'present' && editRulesForm.type===2">
          <el-input
            v-model="editRulesForm.user_id"
            clearable
            placeholder="请输入用户ID（多个请用英文逗号隔开）"
          ></el-input>
        </el-form-item>
        <el-form-item label="赠送天数" v-if="dialogStatus === 'present'">
          <el-radio-group v-model="days1" @change="handleChange">
            <el-radio :label="7">7</el-radio>
            <el-radio :label="15">15</el-radio>
            <el-radio :label="30">30</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="自定义天数" v-if="dialogStatus === 'present'">
          <el-input
            v-model.number="days2"
            clearable
            placeholder="请输入自定义天数"
            @input="handleInput"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="dialogFormVisible = false">返回</el-button>
          <el-button type="primary" @click="submitForm('editRulesForm')">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { frameDelete, frameList, frameCreate, frameUpdate, frameDetail, frameGive } from '@/api/content/borderManagement'

export default {
  data() {
    return {
      days1: undefined,
      days2: undefined,
      giveShowDetailPicture: [],
      giveShowPicture: [],
      adType: [
        { value: 1, label: '房间' },
        { value: 2, label: '用户' }
      ],
      // 要修改的当前行的idsearchSubmit
      row_id: 0,
      editRulesForm: {
        name: undefined,
        type: undefined,
        index_img: undefined,
        room_img: '',
        recommend_img: '',
        days1: undefined,
        days2: undefined
      },
      // 表单规则
      editRulesFormRules: {
        name: [
          {
            required: true,
            message: '请输入名称1-20字符',
            trigger: 'blur',
            min: 1,
            max: 20
          }
        ],
        room_id: [{ required: true, message: '请输入赠送房间号', trigger: 'change' }],
        user_id: [{ required: true, message: '请输入赠送用户号', trigger: 'change' }],
        days: [{ required: true, message: '请选择或输入赠送天数', trigger: 'change' }],
        index_img: [{ required: true, message: '请上传首页效果图', trigger: 'change' }],
        room_img: [{ required: true, message: '请上传房间效果图', trigger: 'change' }],
        recommend_img: [{ required: true, message: '请上传推荐效果图', trigger: 'change' }],
        type: [{ required: true, message: '请选择类型', trigger: 'change' }],
      },
      dialogStatus: '',
      // dialog的头部信息
      titleMap: {
        update: '编辑',
        create: '新增',
        present: '赠送'
      },
      dialogFormVisible: false,
      deleteDialogVisible: false,
      listLoading: false,
      menuList: [],
      limitList: [],
      listQuery: {
        page: 1,
        perPage: 10,
        keyword: undefined,
        display: undefined
      },
      total: 0,
      // 要删除的内容的ids
      dataIds: '',
      options: [],
      skippArr: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
			for (let key in this.listQuery) {
				this.listQuery[key] = this.listQuery[key] === '' ? undefined : this.listQuery[key]
			}

      frameList(this.listQuery).then(response => {
        response.data.list.forEach(element => {
          element.srcList = []
          element.srcList.push(element.room_img)
          element.srcList.push(element.recommend_img)
          element.srcList.push(element.index_img)
        });
        this.menuList = response.data.list
        this.total = response.data.meta.total
        this.listLoading = false
      })
    },
    handleSuccess() {
      this.editRulesForm.index_img = this.ossLastImgUrl
      console.log(this.editRulesForm)
    },
    handleSuccess1() {
      this.editRulesForm.recommend_img = this.ossLastImgUrl
    },
    handleSuccess2() {
      this.editRulesForm.room_img = this.ossLastImgUrl
    },
    // 点击新增
    handleCreate() {
      // this.resetForm('editRulesForm')
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    // 点击编辑
    handleUpdateOrPresent(row, status) {
      this.editRulesForm = JSON.parse(JSON.stringify(row))
      if(status === 'update') {
        this.dialogStatus = 'update'
      }
      if(status === 'present') {
        this.dialogStatus = 'present'
      }
      this.dialogFormVisible = true
    },
    handleCloseDialog(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].clearValidate() // 清除整个表单的校验
      }
      this.days1 = null
      this.days2 = null
      this.resetForm(formName)
    },

    // 重置表单内容
    resetForm(formName) {
      this.$nextTick(() => {
        if (this.$refs[formName] !== undefined) {
          this.$refs[formName].resetFields()
        }
        this.editRulesForm = {
          name: undefined,
          type: undefined,
          index_img: undefined,
          room_img: '',
          recommend_img: ''
        }
      })
    },
    submitForm(formName) {

      this.$refs[formName].validate(valid => {
        if (valid) {
          if(this.dialogStatus === 'present'){
            if(!this.editRulesForm.days) {
              this.$notify({
                  type: 'warning',
                  message: '请选择或输入赠送天数',
                  position: 'bottom-right',
                  showClose: false,
                  duration: 3000
                })
              return false
            }
            const presentData = {
              frame_id: this.editRulesForm.id,
              user_id: this.editRulesForm.user_id,
              room_id: this.editRulesForm.room_id,
              days: this.editRulesForm.days
            }
            frameGive(presentData).then(response => {
              if (response.code === 200) {
                this.getList()
                this.dialogFormVisible = false
                this.$notify({
                  type: 'success',
                  message: '操作成功',
                  position: 'bottom-right',
                  showClose: false,
                  duration: 3000
                })
              }
            })
          }else if(this.dialogStatus === 'update') {
            const updateData = {
              id: this.editRulesForm.id,
              name: this.editRulesForm.name,
              type: this.editRulesForm.type,
              index_img: this.editRulesForm.index_img,	
              recommend_img	: this.editRulesForm.recommend_img,	
              room_img: this.editRulesForm.room_img
            }
            frameUpdate(updateData).then(response => {
              if (response.code === 200) {
                this.getList()
                this.dialogFormVisible = false
                this.$notify({
                  type: 'success',
                  message: '操作成功',
                  position: 'bottom-right',
                  showClose: false,
                  duration: 3000
                })
              }
            })
          }else {
            const createData = {
              name: this.editRulesForm.name,
              type: this.editRulesForm.type,
              index_img: this.editRulesForm.index_img,	
              recommend_img	: this.editRulesForm.recommend_img,	
              room_img: this.editRulesForm.room_img
            }
            frameCreate(createData).then(response => {
              if (response.code === 200) {
                this.getList()
                this.dialogFormVisible = false
                this.$notify({
                  type: 'success',
                  message: '操作成功',
                  position: 'bottom-right',
                  showClose: false,
                  duration: 3000
                })
              }
            })
          }
            
        } else {
          return false
        }
      })
    },
    // 勾选
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 点击单个删除
    handleDelete(row) {
      this.dataIds = { id: `${row.id}` }
      this.deleteDialogVisible = true
    },
    // 点击批量删除
    handleDeleteAll() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          message: '请先勾选要删除的内容',
          type: 'warning'
        })
        return
      } else if (this.multipleSelection.length !== 0) {
        let ids = ''
        for (let key in this.multipleSelection) {
          ids += `${this.multipleSelection[key].id},`
        }
        ids = ids.substring(0, ids.length - 1)
        this.dataIds = { ids: ids }
      }
      this.deleteDialogVisible = true
    },
    // 确定删除
    confirmDelete() {
      this.deleteDialogVisible = false
      frameDelete(this.dataIds).then(response => {
        if (response.code === 200) {
          this.getList()
          this.deleteDialogVisible = false
          this.$notify({
            type: 'success',
            message: '操作成功',
            position: 'bottom-right',
            showClose: false,
            duration: 3000
          })
        }
      })
    },
    handleChange(val){
      this.editRulesForm.days = val
      this.days2 = undefined
    },
    handleInput(val) {
      val = val.replace(/\D/g,'')
      this.days2 = val
      this.editRulesForm.days = val
      this.days1 = null
      console.log(this.days2)
      // this.value=this.value.replace(/\D/g,'')
    }
  }
}
</script>

<style scoped>
[v-cloak] {
  display : none;
}

.clearfix:before,
.clearfix:after {
  display : table;
  content : "";
}

.clearfix:after {
  clear : both;
}

.box-card {
  width : 100%;
}

.demo-form-inline {
  float : right;
}

::v-deep .el-upload-list__item {
  transition : none !important;
}
::v-deep  .el-card__header {
  padding-bottom : 0;
}
::v-deep.avatar-uploader .el-upload {
  border        : 1px dashed #d9d9d9;
  border-radius : 6px;
  cursor        : pointer;
  position      : relative;
  overflow      : hidden;
}

.avatar-uploader .el-upload:hover {
  border-color : #409eff;
}

.avatar-uploader-icon {
  font-size   : 28px;
  color       : #8c939d;
  width       : 100px;
  height      : 100px;
  line-height : 100px;
  text-align  : center;
}

.avatar {
  width   : 100px;
  height  : 100px;
  display : block;
}
</style>
